import { useState, useEffect } from "react";
import type { SkuListItem } from "../set_Sku_data";
import type { CategoryGetReturnItemModel } from "@/api/modules/category";
import type { GoodsItemModel, GoodsItemskuListModel, MyGoodsListSendModel } from "@/api/modules/goods";
import { myGoodsDetail, myGoodsList } from "@/api/modules/goods";
import { categoryGetTwo } from "@/api/modules/category";
import { goodsSkuListDeleteList, goodsSkuListModifyList } from "@/api/modules/goodsSkuList";
import { useNavigate } from "react-router-dom";

import Cimage from "@/components/Cimage";
import { SearchOutlined, PlusOutlined } from "@ant-design/icons";
import { InputNumber, Radio, Form, Button, Table, Space, Modal, Input, message, RadioChangeEvent } from "antd";
import Ccascader from "@/components/Ccascader";
import "./index.less";
import { tableColumns, tableDialogColumns } from "./tableColums";
const goodsList = () => {
	const { Search } = Input;
	const navigate = useNavigate();
	const [loading, setLoading] = useState<boolean>(false);
	// 获取商品列表数据
	const [listQuery, setListQuery] = useState<MyGoodsListSendModel>({
		page: 1,
		size: 10,
		categoryTwoId: null,
		value: "",
		total: 0
	});
	const [goodsData, setGoodsData] = useState<GoodsItemModel[]>([]);
	async function getList(listQueryRef: MyGoodsListSendModel) {
		setLoading(true);
		// 获取商品数据
		myGoodsList(listQueryRef)
			.then(({ code, data }) => {
				if (code === 0) {
					setListQuery({
						...listQueryRef,
						total: data!.total
					});
					setGoodsData(data!.list);
				}
			})
			.finally(() => {
				setLoading(false);
			});
	}
	// 分类筛选回调
	function onCategoryIdChange(value: number | string) {
		const listQueryRef: MyGoodsListSendModel = {
			...listQuery,
			categoryTwoId: value as number
		};
		setListQuery(listQueryRef);
		getList(listQueryRef);
	}
	// 表格分类回显文字部分
	const [categoryTwoData, setCategoryTwoData] = useState<CategoryGetReturnItemModel[]>();
	async function getCategoryTwo() {
		// 获取二级分类
		categoryGetTwo().then(({ code, data }) => {
			if (code === 0) setCategoryTwoData(data);
		});
	}
	function categoryFilter(parentId: number | string) {
		if (categoryTwoData?.length === 0) return "空";
		let categoryName = "";
		categoryTwoData?.forEach(item => {
			if (item.id === parentId) categoryName = item.name;
		});
		return categoryName;
	}
	const onSearch = (value: string) => {
		const listQueryRef: MyGoodsListSendModel = {
			...listQuery,
			value
		};
		setListQuery(listQueryRef);
		getList(listQueryRef);
	};
	useEffect(() => {
		getCategoryTwo();
		getList(listQuery);
	}, []);
	// 分页器变化回调
	function handleTableChange(pagination: any) {
		const listQueryRef: MyGoodsListSendModel = {
			page: pagination.current,
			size: pagination.pageSize,
			total: pagination.total
		};
		setListQuery(listQueryRef);
		getList(listQueryRef);
	}
	// 查看规格列表弹窗相关
	interface Dialog<T = SkuListItem, K = GoodsItemskuListModel> {
		visible: boolean;
		title: string;
		skuListItem: T[];
		skuData?: K[];
		goodsId?: number;
	}
	const [dialog, setDialog] = useState<Dialog>({
		visible: false,
		title: "",
		skuListItem: [], // 规格列表数组
		skuData: [] // 规格信息数组
	});
	// 打开查看规格列表弹窗
	const openDialog = async (goodsId: number) => {
		const { setSku_list } = await import("@/views/goods/set_Sku_data");
		const { code, data } = await myGoodsDetail({ goodsId });
		if (code === 0) {
			const newDialog: Dialog = {
				visible: true,
				title: data!.name,
				goodsId,
				skuData: data?.skuList,
				skuListItem: []
			};
			// 无规格商品
			if (data?.none_sku) newDialog.skuListItem = setSku_list(data as GoodsItemModel, "none");
			// 多规格商品
			else newDialog.skuListItem = setSku_list(data as GoodsItemModel, "");
			console.log("newDialog", newDialog);
			setDialog(newDialog);
		}
	};
	// 关闭查看规格列表弹窗
	const closeDialog = () => {
		setDialog({
			visible: false,
			title: "",
			skuListItem: [], // 规格列表数组
			skuData: [] // 规格信息数组
		});
	};
	// 规格列表修改表单模态框
	interface SkuDialog {
		visible: boolean;
		title: string;
		price: string; // sku价格
		skuValue: { [propName: string]: any }; // 已选择的sku规格
		parentId: number; // 商品id
		id?: number; // 当前sku Id
		stock_num?: number; // sku当前库存
	}
	const [form] = Form.useForm();
	const [skuDialog, setSkuDialog] = useState<SkuDialog>({
		visible: false,
		title: "",
		price: "",
		skuValue: {},
		parentId: 0
	});
	const [confirmSkuDialogLoading, setConfirmSkuDialogLoading] = useState<boolean>(false);

	const handleSkuDialogOk = () => {
		form.submit();
	};
	// 打开修改sku规格弹窗
	const openSkuDailog = (row: SkuListItem) => {
		// 打开规格列表模态框
		const newSkuDialog: SkuDialog = {
			visible: true,
			title: "修改规格信息",
			id: row._id,
			parentId: row.goods_id,
			stock_num: row.stock,
			price: row.price,
			skuValue: {}
		};
		const newDialog = {
			...dialog
		};
		// 初始化已选择的sku ID (vId)
		row.indexList.forEach(item => {
			newDialog.skuData![item.parentIndex].vId = newDialog.skuData![item.parentIndex].v[item.sonIndex].id;
			newSkuDialog.skuValue[newDialog.skuData![item.parentIndex].k_s] = newDialog.skuData![item.parentIndex].v[item.sonIndex].id;
		});
		// 修改的时候回显数据
		form.setFieldsValue({
			price: row.price,
			stock_num: row.stock,
			...newSkuDialog.skuValue
		});
		setDialog(newDialog);
		setSkuDialog(newSkuDialog);
	};
	// 关闭修改sku规格弹窗
	function closeSkuDialog() {
		setSkuDialog({
			visible: false,
			title: "",
			price: "",
			skuValue: {},
			parentId: 0,
			stock_num: 0,
			id: 0
		});
	}
	// 选择sku规格回调
	function skuFormSkuChange(item: GoodsItemskuListModel, e: RadioChangeEvent) {
		console.log("skuFormSkuChange", item, e.target.value);
		// 选择单项规格回调
		item.vId = e.target.value;
		const skuDialogRef = {
			...skuDialog
		};
		skuDialogRef.skuValue[item.k_s] = item.vId;
		setSkuDialog(skuDialogRef);
	}
	// 提交修改sku规格表单
	const onSkuDialogFinish = async (form: any) => {
		console.log("form", form);
		setConfirmSkuDialogLoading(true);
		const params = {
			id: skuDialog.id,
			parentId: skuDialog.parentId,
			stock_num: form.stock_num,
			price: form.price,
			...skuDialog.skuValue
		};
		console.log("params", params);
		goodsSkuListModifyList(params)
			.then(({ code, msg }) => {
				if (code === 0) {
					message.success(msg);
					openDialog(skuDialog.parentId); // 刷新数据
					closeSkuDialog();
				}
			})
			.finally(() => {
				setConfirmSkuDialogLoading(false);
			});
	};
	// 修改sku规格表单失败回调
	const onSkuDialogFinishFailed = (errorInfo: any) => {
		message.warning("请检查表单填写是否正确！");
		console.log("Failed:", errorInfo);
	};
	// 删除sku规格
	const removeSkuList = (skuListId: number, goodsId: number) => {
		setConfirmSkuDialogLoading(true);
		goodsSkuListDeleteList({ ids: skuListId.toString() })
			.then(({ code, msg }) => {
				if (code === 0) {
					message.success(msg);
					openDialog(goodsId); // 刷新数据
				}
			})
			.finally(() => {
				setConfirmSkuDialogLoading(false);
			});
	};
	// 跳转到添加商品页
	function toAddGoods(goodsId?: number) {
		if (!goodsId) {
			navigate(`/Goods/add`);
			return;
		} else {
			navigate(`/Goods/add?goodsId=${goodsId}`);
		}
	}
	// 跳转到商品详情页
	function toGoodsDetail(goodsId: number) {
		if (!goodsId) {
			message.warning("请选择商品");
			return;
		}
		navigate(`/Goods/detail?goodsId=${goodsId}`);
	}
	// 表格列
	const columns: any[] = tableColumns(categoryFilter, openDialog, toAddGoods, toGoodsDetail);
	const dialogColumns: any[] = tableDialogColumns(openSkuDailog, removeSkuList);
	return (
		<div className="goodsList">
			<div className="goodsList__title flex items-center justify-between mb-10">
				<Space className="flex items-center" size="large">
					<span className="text-18 font-bold">商品列表</span>
					<Ccascader onChange={onCategoryIdChange} />
					<Search placeholder="输入商品关键字搜索" allowClear onSearch={onSearch} style={{ width: 200 }} />
				</Space>
				<Space className="flex items-center">
					<Button
						icon={<PlusOutlined />}
						onClick={() => {
							toAddGoods();
						}}
					>
						新增商品
					</Button>
					<Button
						type="primary"
						icon={<SearchOutlined />}
						onClick={() => {
							getList(listQuery);
						}}
					>
						查询
					</Button>
				</Space>
			</div>
			<div className="goodsList__content">
				<Table
					loading={loading}
					bordered={false}
					dataSource={goodsData}
					columns={columns}
					rowKey={record => record.id}
					scroll={{ x: true }}
					pagination={{
						current: listQuery.page, // 当前页码
						pageSize: listQuery.size, // 每页条数
						total: listQuery.total, // 数据总数
						showSizeChanger: true, // 显示每页条数切换器
						showQuickJumper: true // 显示快速跳转输入框
					}}
					onChange={pagination => handleTableChange(pagination)} // 分页变化回调
				/>
			</div>
			{/* 查看规格列表弹窗 */}
			<Modal width={750} title={dialog.title} open={dialog.visible} footer={null} onCancel={closeDialog}>
				<Table
					loading={loading}
					bordered={false}
					dataSource={dialog.skuListItem}
					columns={dialogColumns}
					rowKey={record => record._id}
					pagination={false}
				/>
			</Modal>
			{/* 修改sku规格弹窗 */}
			<Modal
				width={600}
				title={skuDialog.title}
				open={skuDialog.visible}
				destroyOnClose={true}
				onOk={handleSkuDialogOk}
				confirmLoading={confirmSkuDialogLoading}
				onCancel={closeSkuDialog}
			>
				<Form
					form={form}
					preserve={false}
					size="middle"
					autoComplete="off"
					onFinish={onSkuDialogFinish}
					onFinishFailed={onSkuDialogFinishFailed}
				>
					<Form.Item
						label="价格"
						name="price"
						rules={[
							{ required: true, message: "请输入该选项价格" },
							{
								pattern: /^\d+(\.\d{0,2})?$/,
								message: "最多保留两位小数！"
							}
						]}
					>
						<InputNumber max={9999999} precision={2} min={0} step={1} className="w-full!" addonAfter={<>￥</>} />
					</Form.Item>
					<Form.Item
						label="库存"
						name="stock_num"
						rules={[
							{ required: true, message: "请输入该选项剩余库存" },
							{
								pattern: /^-?\d+$/,
								message: "请输入整数！"
							}
						]}
					>
						<InputNumber className="w-full!" max={9999999} precision={0} min={0} step={1}></InputNumber>
					</Form.Item>
					{dialog.skuData?.map((item, index) => (
						<Form.Item label={item.k} name={item.k_s} key={index} rules={[{ required: true, message: "请选择规格项" }]}>
							<Radio.Group optionType="button" buttonStyle="solid" onChange={e => skuFormSkuChange(item, e)}>
								{item.v.map((song, idx) => (
									<Radio value={song.id} key={idx}>
										<Space>
											{song.previewImgUrl && song.previewImgUrl?.length > 0 ? (
												<Cimage src={song.previewImgUrl[0].url} width={30} height={30} isPreview={false}></Cimage>
											) : null}
											<span>{song.name}</span>
										</Space>
									</Radio>
								))}
							</Radio.Group>
						</Form.Item>
					))}
				</Form>
			</Modal>
		</div>
	);
};
export default goodsList;
